# -*- coding:utf-8 -*-
# time: 2025/7/31 ♡  15:37
# author:张伟
import requests

# headers = {
#     "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1Mzk0NzMwMywianRpIjoiOTI2MjBlY2YtNjVlNS00YWU4LWEwMzUtYzAzZDZhNDE0ZTA3IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6Ik1yamlENzg4dEpWaGVnUUwyejZ5TlIiLCJuYmYiOjE3NTM5NDczMDMsImNzcmYiOiJjYjdhMDQyMS1kY2E2LTRiNGItYjc0Yy1lZDdhOTRmOTE1MWEiLCJleHAiOjE3NTM5NDgyMDN9.Pb1E9se3p-Dhd4smiggO2MIXMFXAFEJZt3kVFdbvo50"
# }
#
# resp = requests.get("http://127.0.0.1:5000/cmsapi/", headers=headers)
# print(resp.text)


from datetime import datetime
from app import app
from flask_jwt_extended import get_jwt, decode_token


# 方法1: 使用 decode_token 解码 JWT token
def check_jwt_expiration(token):
    """
    检查 JWT token 的过期时间
    :param token: JWT token 字符串
    """
    try:
        # 解码 token 获取载荷信息
        decoded_token = decode_token(token)
        exp_timestamp = decoded_token.get('exp')

        if exp_timestamp:
            exp_datetime = datetime.fromtimestamp(exp_timestamp)
            current_time = datetime.now()

            print(f"JWT 过期时间: {exp_datetime}")
            print(f"当前时间: {current_time}")
            print(f"时间戳: {exp_timestamp}")

            if exp_datetime > current_time:
                print("Token 仍然有效")
            else:
                print("Token 已过期")
        else:
            print("Token 中没有设置过期时间")

    except Exception as e:
        print(f"解码 token 时出错: {e}")


# 方法2: 如果你已经有了有效的 JWT 上下文
def check_jwt_in_context():
    """
    在已有 JWT 上下文中检查过期时间
    """
    with app.app_context():
        try:
            jwt_data = get_jwt()
            exp_timestamp = jwt_data.get('exp')

            if exp_timestamp:
                exp_datetime = datetime.fromtimestamp(exp_timestamp)
                print(f"JWT 过期时间: {exp_datetime}")
                print(f"时间戳: {exp_timestamp}")
            else:
                print("Token 中没有设置过期时间")
        except Exception as e:
            print(f"获取 JWT 信息时出错: {e}")


# 使用示例
if __name__ == "__main__":
    # 替换为你的实际 JWT token
    jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1Mzk3MzE4MCwianRpIjoiNzliZGYzNDAtNDg2Yy00ZjY3LWI5M2ItYTFkMDg3NzlmYzVkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6Ik1yamlENzg4dEpWaGVnUUwyejZ5TlIiLCJuYmYiOjE3NTM5NzMxODAsImNzcmYiOiJhMjE0NjE3YS01YmI2LTQxZWMtYjNhZS0yY2Q1ZjhiMDUzN2MiLCJleHAiOjE3NTQ1Nzc5ODB9.dAnq4NO6hNMF1fsFVMlwCvr8csdK-hGdoz8A6gbWTRk"

    # 检查 JWT 过期时间
    with app.app_context():
        check_jwt_expiration(jwt_token)

    # 如果需要在应用上下文中检查
    # check_jwt_in_context()
